package com.ks.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ks.handler.BusinessException;
import com.ks.response.Result;
import com.ks.response.ResultCode;
import com.ks.system.entity.User;
import com.ks.system.service.AliOssService;
import com.ks.system.service.UserService;
import com.ks.system.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ks
 * @since 2020-12-01
 */
@Api(value = "系统用户模块", tags = "系统用户接口")
@RestController
@RequestMapping("/system/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private AliOssService aliOssService;


    /**
     * 分页查询全部
     *
     * @return
     */
    @PostMapping("/findAll")
    @ApiOperation(value = "查询所有用户信息", notes = "查询所有用户信息")
    public Result findAll(@RequestParam(required = true, defaultValue = "1") Integer current,
                          @RequestParam(required = true, defaultValue = "6") Integer size,
                          @RequestBody UserVo userVo) {
        /*对用户进行分页  泛型中注入的就是用户类*/
        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> wapper = getWapper(userVo);
        IPage<User> userPage = userService.findAll(page, wapper);
        /* Page<User> userPage = userService.page(page);*/
        if (userPage != null) {
            /*总条数*/
            long total = userPage.getTotal();
            /*数据*/
            List<User> userList = userPage.getRecords();
            return Result.ok().data("total", total).data("userList", userList);
        } else {
            throw new BusinessException(ResultCode.ARITHMETIC_EXCEPTION.getCode(),
                    ResultCode.ARITHMETIC_EXCEPTION.getMessage());
        }
    }

    /**
     * 封装判断userVo是否为空
     *
     * @param userVo
     * @return
     */
    private QueryWrapper<User> getWapper(UserVo userVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (userVo != null) {
            if (!StringUtils.isEmpty(userVo.getDepartmentId()) && userVo.getDepartmentId() != 0) {
                wrapper.eq("department_id", userVo.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVo.getEmail())) {
                wrapper.eq("email", userVo.getEmail());
            }
            if (!StringUtils.isEmpty(userVo.getNickname())) {
                wrapper.like("nickname", userVo.getNickname());
            }
            if (!StringUtils.isEmpty(userVo.getSex())) {
                wrapper.eq("sex", userVo.getSex());
            }
            if (!StringUtils.isEmpty(userVo.getUsername())) {
                wrapper.like("username", userVo.getUsername());
            }
        }
        return wrapper;
    }

    /**
     * 根据用户id进行查询
     * @param id
     * @return
     */
    @GetMapping("/findById")
    @ApiOperation(value = "根据id进行查询", notes = "根据id查询用户信息")
    public Result findById(Integer id) {
        User user = userService.getBaseMapper().selectById(id);
        if (user != null) {
            return Result.ok().data("user", user);
        } else {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
    }


    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/getUserList")
    public Result getUserList(@RequestParam(required = true, defaultValue = "1") Integer current,
                              @RequestParam(required = true, defaultValue = "6") Integer size,
                              @RequestBody UserVo userVo) {
        Page<User> page = userService.getUserList(userVo, new Page<User>(current, size));
        return Result.ok().data("page", page);
    }


    /**
     * 根据用户id进行删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除用户信息", notes = "逻辑删除 修改状态")
    @PostMapping("/delById")
    public Result delById(@RequestParam(required = true) Integer id) {
        boolean result = false;
        User user = userService.getBaseMapper().selectById(id);
        if (user != null) {
            user.setDeleted(true);
            int i = userService.getBaseMapper().updateById(user);
            if (i > 0) {
                result = true;
                return Result.ok().data("result", result);
            }
        } else {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        return null;
    }


    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @ApiOperation(value = "修改用户信息", notes = "根据id修改用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {
        try {
            userService.getBaseMapper().updateById(user);
            return Result.ok();
        } catch (Exception e) {
            //打印错误日志
            return Result.error();
        }
    }

    /**
     * 新增用户信息
     * @param user
     * @return
     */
    @ApiOperation(value = "添加用户",notes = "添加用户")
    @PostMapping("/AddUser")
    public Result AddUser(@RequestBody User user) {
        try {
            userService.addUser(user);
            return Result.ok();
        } catch (Exception e) {
            //打印错误日志
            return Result.error();
        }
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @ApiOperation("Oss上传文件")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        String upload = aliOssService.upload(file);
        return Result.ok().message(upload);
    }

    /**
     * 导出用户excel
     * @param response
     * @param userVO
     * @throws IOException
     */
    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, @RequestBody(required = false) UserVo userVO) throws IOException {
        QueryWrapper<User> wrapper = getWapper(userVO);
        List<User> users = userService.list(wrapper);
        userService.exportUserExcel(response,users);
    }
}

